package com.szxy.miaosha.service.impl;

import com.szxy.miaosha.dao.MiaoShaUserDao;
import com.szxy.miaosha.domain.MiaoshaUser;
import com.szxy.miaosha.exception.GlobalException;
import com.szxy.miaosha.redis.MiaoShaUserPrefixKey;
import com.szxy.miaosha.redis.RedisService;
import com.szxy.miaosha.service.MiaoShaUserService;
import com.szxy.miaosha.utils.CodeMsg;
import com.szxy.miaosha.utils.Constant;
import com.szxy.miaosha.utils.Md5Util;
import com.szxy.miaosha.utils.UUIDUtil;
import com.szxy.miaosha.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: zwz
 * @Date:2020/9/6 21:58
 * @Description:com.szxy.miaosha.service.impl
 * @Version:1.0
 **/
@Service
public class MiaoShaUserServiceImpl implements MiaoShaUserService {


    @Autowired
    private MiaoShaUserDao miaoShaUserDao;
    @Autowired
    private RedisService redisService;

    @Override
    public String login(LoginVo loginVo, HttpServletResponse resp) throws GlobalException {
        String mobile = loginVo.getMobile();
        String password = loginVo.getPassword();
        MiaoshaUser miaoshaUser = miaoShaUserDao.getById(Long.parseLong(mobile));
        // 查询不到用户
        if (miaoshaUser == null) {
            throw new GlobalException(CodeMsg.USER_NOT_EXIST);
        }
        // 构造数据库密码
        String dbPass = Md5Util.inputPassToDbPass(password, miaoshaUser.getSalt());
        if (!miaoshaUser.getPassword().equals(dbPass)) {
            throw new GlobalException(CodeMsg.PASSWORD_ERROR);
        }
        // 将密码赋空
        // miaoshaUser.setPassword(null);
        // 生成 Redis  key 的值
        String token = UUIDUtil.generateUuid();
        addCookie(resp, token, miaoshaUser);
        return token;
    }

    /**
     * 添加 cookie 信息
     *
     * @param resp        HttpServletResponse
     * @param token
     * @param miaoshaUser MiaoShaUser
     */
    private void addCookie(HttpServletResponse resp, String token, MiaoshaUser miaoshaUser) {
        redisService.set(MiaoShaUserPrefixKey.SESSION_TOKEN, token, miaoshaUser);
        // 创建 Cookies
        Cookie cookie = new Cookie(Constant.COOKIES_TOKEN_KEY, token);
        cookie.setPath("/");
        cookie.setMaxAge(MiaoShaUserPrefixKey.SESSION_TOKEN.expireSeconds());
        resp.addCookie(cookie);
    }

    @Override
    public MiaoshaUser getByToken(HttpServletResponse resp, String token) {
        if (token == null ||  token.isEmpty()) {
            return null;
        }
        MiaoshaUser miaoshaUser = redisService.get(MiaoShaUserPrefixKey.SESSION_TOKEN, token, MiaoshaUser.class);
        if (miaoshaUser != null) {
            addCookie(resp, token, miaoshaUser);
        }
        return miaoshaUser;
    }
}
